import { LOGIN_TOKEN } from '@/global/constants'
import { localCache } from '@/utils/cache'
import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, CreateAxiosDefaults } from 'axios'

class HYRequest {
  instance: AxiosInstance

  // 每一个 request 实例中都包含一个 axios 的实例
  constructor(config: CreateAxiosDefaults) {
    this.instance = axios.create(config)

    // 每个 instance 实例都添加拦截器
    this.instance.interceptors.request.use(
      (config) => {
        const token = localCache.getCache(LOGIN_TOKEN)
        if (token) {
          config.headers['Authorization'] = 'Bearer ' + token
        }

        return config
      },
      (err) => {
        return err
      }
    )

    this.instance.interceptors.response.use(
      (res) => {
        console.log('响应拦截器生效')
        return res.data
      },
      (err) => {
        return err
      }
    )
  }

  // 封装网络请求的方法
  request<R = any>(config: AxiosRequestConfig) {
    return this.instance.request<any, R>(config)
  }

  get<R = any>(config: AxiosRequestConfig) {
    return this.request<R>({ ...config, method: 'GET' })
  }

  post<R = any>(config: AxiosRequestConfig) {
    return this.request<R>({ ...config, method: 'POST' })
  }

  delete<R = any>(config: AxiosRequestConfig) {
    return this.request<R>({ ...config, method: 'DELETE' })
  }

  patch<R = any>(config: AxiosRequestConfig) {
    return this.request<R>({ ...config, method: 'PATCH' })
  }
}

export default HYRequest
